package com.zoweunion.mechanic.plugins.shiro;

import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.service.base.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;

@Service
public class MyRealm extends AuthorizingRealm {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyRealm.class);
    
    @Autowired
    private UserService userService;

    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException{
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);
        if (username == null) {
            throw new AuthenticationException("token有误");
        }

        User user = userService.getUserByAccount(username);
        if (user == null) {
            throw new AuthenticationException("用户不存在");
        }

        if (!JWTUtil.verify(token, username,user.getUser_password())) {
            throw new AuthenticationException("认证失败,请重新登录");
        }

        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }

    /**
     * 权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	LOGGER.info("权限认证...");
    	String username = JWTUtil.getUsername(principals.toString());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 查询user对应的角色并添加
        Map<String, Object> userInfo = userService.getUserInfoByAccount(username);
        simpleAuthorizationInfo.setRoles(Collections.singleton(userInfo.get("role_name").toString()));
        return simpleAuthorizationInfo;
    }
}